package com.sms.plateform.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.sms.plateform.common.finals.Constants;
import com.sms.plateform.kernel.entity.UserInfo;
import com.sms.plateform.kernel.entity.UserRole;
import com.sms.plateform.kernel.service.IGroupInfoService;
import com.sms.plateform.kernel.service.IUserInfoService;
import com.sms.plateform.kernel.service.IUserRoleService;

@Controller
public class LoginController extends BaseController{
	
	@Autowired
	private IUserInfoService userInfoService;
	@Autowired
	private IGroupInfoService groupInfoService;
	@Autowired
	private IUserRoleService userRoleService;
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/login")
	public String indexHandel(HttpServletRequest request, HttpServletResponse response,ModelMap model) {
		String action = this.getUrlParam(request, "action");
		String msg=this.getUrlParam(request, "msg");
		if("do".equals(action)){
			Map<String, Object> param = new HashMap<String, Object>();
			String username = this.getUrlParam(request, "user");
			param.put("username", username);
			List<UserInfo> userInfoForLogin = userInfoService.listModel(param);
			if(userInfoForLogin.size() > 0){
				UserInfo userInfo = userInfoForLogin.get(0);
				String password = this.getUrlParam(request, "pwd");
				if(password.equals(userInfo.getPassword())){
					//获取用户配置信息
					param.put("id", userInfo.getGid());
					param.put("password", userInfo.getPassword());
					HashMap hashMap=this.groupInfoService.getUserGroupPriceInfo(param);
					param.clear();
					param.put("uid", userInfo.getId());
					List<UserRole> userRole = userRoleService.listModel(param);
					if(null != userRole && userRole.size()>0){
						this.setSessionObject(request, Constants.SESSION_ROLE, userRole.get(0));
					}
					this.setSessionObject(request, Constants.SESSION_GROUP, hashMap);
					this.setSessionObject(request, Constants.SESSION_USER, userInfo);
					return "redirect:index.do";
				} else {
					model.put("msg", "密码错误,请重试.");
					return "login/login";
				}
			} else {
				model.put("msg", "该用户名不存在,请重新登录.");
				return "login/login";
			}
		}
		model.put("msg", msg);
		return "login/login";
	}
	
	@RequestMapping("/logout")
	public ModelAndView logoutHandel(HttpServletRequest request, HttpServletResponse response) {
		request.getSession().removeAttribute(Constants.SESSION_USER);
		request.getSession().removeAttribute(Constants.SESSION_ROLE);
		return new ModelAndView("redirect:index.do");
		
	}
	
}